package com.joyintech.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Maps;
import com.joyintech.dao.FileMapper;
import com.joyintech.model.FileUrl;
import com.joyintech.service.FileService;
import com.joyintech.util.AppReply;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


/**
 * @author LENOVO
 */
@Validated
@Controller
@Slf4j
@RequestMapping("/file")
public class FileController {


    @Autowired
    FileService fileService;

    @Resource
    FileMapper fileMapper;

    /**
     * 上传文件
     *
     * @param file    上传文件
     * @param project 业务系统名称
     *                http://172.29.101.10:2005/image1/2024/08/02/acb32a2c-26df-4fd6-8ee6-d3a0552ac4b4.png
     *                http://101.133.149.13/api/image1/2024/08/02/312de868-5c39-4ba4-90cc-b174373a8401.png
     * @return
     */
    @PostMapping(value = "/upload")
    public @ResponseBody AppReply fileupload(@RequestPart("file") MultipartFile file,
                                             @RequestParam("project") String project) {
        if (file == null || file.isEmpty()) {
            return AppReply.error("file 参数不能为空");
        }

        if (!checkFileType(file.getOriginalFilename())) {
            return AppReply.error("file 格式错误");
        }

        try {
            if (!checkFile(file)) {
                return AppReply.error("上传的文件异常");
            }
        } catch (Exception e) {
            return AppReply.error(e.getMessage());
        }
        log.info("fileName ---> OriginalFilename{} Name{}", file.getOriginalFilename(), file.getName());

        try {
            FileUrl fileUrl = fileService.save(file, project);
            Map map = Maps.newHashMap();
            map.put("file_id", fileUrl.getId());
            map.put("value", fileUrl.getRealPath());
            map.put("filename", fileUrl.getFileName());
            map.put("url", fileUrl.getFileUrl());
            return AppReply.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return AppReply.error(e);
        }
    }

    /**
     * 文件列表查询
     *
     * @param images 下载文件的 ids
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping(value = "/fileList")
    public AppReply fileList(@RequestParam(name = "images", required = false) List<String> images) {
        LambdaQueryWrapper<FileUrl> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.in(FileUrl::getId, images);
        queryWrapper.eq(FileUrl::getState, "1");
        List<FileUrl> fileUrls = fileMapper.selectList(queryWrapper);
        return AppReply.success(fileUrls);
    }

    /**
     * 下载文件
     *
     * @param id 下载文件的 id
     * @return
     * @throws Exception
     */
    @ResponseBody
    @GetMapping(value = "/downloadFile")
    public void downloadFile(@RequestParam(name = "id", required = false) Integer id, HttpServletResponse response)
            throws Exception {
        fileService.downloadFile(id, response);
    }

    /**
     * 删除文件
     *
     * @param id 文件 id
     * @return
     */
    @ResponseBody
    @PostMapping("/deleteFile")
    public AppReply deleteFile(@RequestParam("id") Integer id) throws Exception {
        fileService.deleteFile(id);
        return AppReply.success();
    }


    /**
     * checkFileType 校验文件类型是否符合要求
     *
     * @param fileFullName: 文件全路径
     * @return: boolean
     * @since: 1.0.0
     * @Author: jin.xu
     * @Date: 2021/04/15 16:40:18
     * @change: 2021/04/15 16:40:18 by jin.xu for init
     */
    private boolean checkFileType(String fileFullName) {
        if (StringUtils.isBlank(fileFullName)) {
            // 如果文件名为空 说明不符合要求
            log.error("file [" + fileFullName + "] is not support");
            return false;
        } else {
            fileFullName = fileFullName.toLowerCase();

            if (fileFullName.endsWith(".jpg") || fileFullName.endsWith(".jpeg")
                    || fileFullName.endsWith(".png") || fileFullName.endsWith(".txt")
                    || fileFullName.endsWith(".xls") || fileFullName.endsWith(".xlsx")
                    || fileFullName.endsWith(".doc") || fileFullName.endsWith(".docx")
                    || fileFullName.endsWith(".pdf") || fileFullName.endsWith(".rar")
                    || fileFullName.endsWith(".zip") || fileFullName.endsWith(".pptx")
                    || fileFullName.endsWith(".ppt") || fileFullName.endsWith(".xmind")
                    || fileFullName.endsWith(".webp")
            ) {
                log.info("file [" + fileFullName + "] is support");
                return true;
            } else {
                log.error("file [" + fileFullName + "] is not support");
                return false;
            }
        }
    }

    /**
     * checkFile 校验文件是否合规 文件大小校验
     *
     * @param file:
     * @return: boolean
     * @since: 1.0.0
     * @Author: jin.xu
     * @Date: 2021/04/15 19:48:45
     * @change: 2021/04/15 19:48:45 by jin.xu for init 1.spring.servlet.multipart.max-file-size=最大文件大小
     * spring.servlet.multipart.max-request-size=最大文件大小
     */
    private boolean checkFile(MultipartFile file) throws Exception {
        if (file == null) {
            throw new Exception("文件为空");
        }

        // KB
        long fileSize = file.getSize() / 1024;
        String fileFullName = file.getOriginalFilename();

        if (fileFullName.endsWith(".jpg") || fileFullName.endsWith(".jpeg") || fileFullName.endsWith(".png")) {
            if (fileSize > (10 * 1024)) {
                throw new Exception("图片文件大于10MB");
            }
        } else {
            if (fileSize > (500 * 1024)) {
                throw new Exception("文件大于500MB");
            }
        }

        return true;
    }


}
